package com.mappn.backup.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.util.Log;

public class Utils {
	private static final String TAG = "Utils";
	private static Process mProcess;

	/**
	 * 获取安装的apk
	 */
	public static List<PackageInfo> getInstalledApps(Context context) {
		PackageManager pm = context.getPackageManager();
		List<PackageInfo> packages = pm.getInstalledPackages(0);
		List<PackageInfo> packageInfo = new ArrayList<PackageInfo>();
		String ourPackageName = context.getPackageName();
		for (PackageInfo info : packages) {
			if (((info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)
					&& !ourPackageName.equals(info.packageName)) {
				packageInfo.add(info);
			}
		}

		return packageInfo;
	}

	/** 获取apk文件存储位置 **/
	public static HashMap<String, String> getAllApkPath(Context context) {
		PackageManager pm = context.getPackageManager();
		List<ApplicationInfo> appinfoList = pm.getInstalledApplications(0);
		String ourPackageName = context.getPackageName();
		HashMap<String, String> apkPath = new HashMap<String, String>();
		for (ApplicationInfo appInfo : appinfoList) {
			if (((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)
					&& !ourPackageName.equals(appInfo.packageName)) {
				apkPath.put(appInfo.packageName, appInfo.publicSourceDir);
				System.out.println(appInfo.publicSourceDir);
			}
		}
		return apkPath;
	}

	private static String getAppName(Context context, String pkgName) {
		PackageManager pm = context.getPackageManager();
		String appName = null;
		try {
			appName = (String) pm.getApplicationLabel(pm.getApplicationInfo(
					pkgName, PackageManager.GET_UNINSTALLED_PACKAGES));
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return appName;
	}

	public static String runCommond(Process process, int timeout, String commond)
			throws InterruptedException {
		mProcess = process;
		DataOutputStream os = new DataOutputStream(process.getOutputStream());
		BufferedReader is = new BufferedReader(new InputStreamReader(
				new DataInputStream(process.getInputStream())), 64);

		String inLine;

		inLine = executeCommand(os, is, timeout, commond);
		return inLine;
	}

	private static String executeCommand(DataOutputStream os,
			BufferedReader is, int timeout, String... commands)
			throws InterruptedException {
		if (commands.length == 0)
			return null;
		StringBuilder command = new StringBuilder();
		for (String s : commands) {
			command.append(s).append(" ");
		}
		command.append("\n");
		Log.d(TAG, command.toString());
		try {
			os.writeBytes(command.toString());

			if (is != null) {
				if (timeout == 0) {
					WatchThread wt = new WatchThread(mProcess);
					wt.start();
					mProcess.waitFor();
					String ret = wt.getStream();
					wt.setOver(true);
					return ret;
				} else {
					for (int i = 0; i < timeout; i++) {
						if (is.ready())
							break;
						Thread.sleep(5);
					}
					if (is.ready()) {
						return is.readLine();
					} else {
						return null;
					}
				}
			} else {
				return null;
			}
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return null;
	}

	/**
	 * 测试是否可以su
	 * 
	 * @param process
	 * @return
	 */
	public static boolean testSu(Process process) {
		// Just use one try/catch for all the root commands
		// Get root access
		DataOutputStream os = new DataOutputStream(process.getOutputStream());
		BufferedReader is = new BufferedReader(new InputStreamReader(
				new DataInputStream(process.getInputStream())), 64);
		mProcess = process;
		String inLine;
		try {

			inLine = executeCommand(os, is, 60 * 1000, "echo test");

			if (inLine == null || !inLine.equals("test")) {
				return false;
			} else {
				System.out.println(inLine);
				return true;
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	/**
	 * 保存APK icon至sdcard
	 * 
	 * @param context
	 * @param pkgName
	 * @param appName
	 */
	public static void makeIconFile(Context context, String pkgName) {
		String appName = getAppName(context, pkgName);
		// TODO 文件名不存在
		Bitmap bitmap = drawableToBitmap(getLocalAppIcon(context, pkgName));
		FileOutputStream fos = null;
		try {
			File file = new File(Const.ICON_FOLDER + appName + ".png");
			fos = new FileOutputStream(file);
			byte[] imageByte = bitmap2Bytes(bitmap);
			fos.write(imageByte, 0, imageByte.length);
			fos.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static Drawable getLocalAppIcon(Context context, String pkgName) {
		final PackageManager pm = context.getPackageManager();
		Drawable d = null;
		try {
			d = pm.getApplicationIcon(pkgName);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return d;
	}

	private static Bitmap drawableToBitmap(Drawable drawable) {
		Bitmap bitmap = Bitmap
				.createBitmap(
						drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight(),
						drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
								: Bitmap.Config.RGB_565);

		Canvas canvas = new Canvas(bitmap);
		if (drawable.getIntrinsicWidth() < 0
				|| drawable.getIntrinsicHeight() < 0) {
			return null;
		} else {
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable
					.getIntrinsicHeight());
			drawable.draw(canvas);
			return bitmap;
		}
	}

	public static byte[] bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		byte[] byteResult = baos.toByteArray();
		try {
			baos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return byteResult;
	}

	/**
	 * 删除文件
	 * 
	 * @param file
	 */
	public static void deleteFile(File file) {
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();
				for (int i = 0; i < files.length; i++) {
					deleteFile(files[i]);
				}
			}
			file.delete();
		} else {
		}
	}
}
